package com.news.util;

/**
 * 工具类，根据网页输出字返回字符
 */

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.news.contant.Contant;

public class NetUtil {
	final static int BUFFER_SIZE = 4096;
	
	/**
	 * 检测当前网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetAvailable(Context context) {

		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager == null) {
			return false;
		}

		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return false;
		}

		if (NetworkInfo.State.CONNECTED == networkInfo.getState()) {
			return true;
		}
		return false;
	}

	public static String GetHtml(String urlpath) throws Exception {
		URL url = new URL(urlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(6 * 1000);
		conn.setRequestMethod("GET");

		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			String html = InputStreamTOString(inputStream);
			return html;
		}
		return null;
	}

	/**
	 * 根据输入流转换成字符串
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static String InputStreamTOString(InputStream in) throws Exception {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[BUFFER_SIZE];
		int count = -1;
		while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
			outStream.write(data, 0, count);

		data = null;
		return new String(outStream.toByteArray(), Contant.contentCode);// "GBK");//凤凰的是UTF-8,新浪的是GBK
	}
	

}
